#include "button.h"

#include "lualib.h"
#include "lua.h"
#include "lauxlib.h"

#include <string.h>
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>

extern lua_State* g_ufo_lua_state;

static int lua_ufoButtonSetNormalImage(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	const char *texture = lua_tostring(L, -1);
	UFO_Texture tex = ufoResourceGetTexture(texture);
	if (texture) {
		ufoButtonSetNormalImage(view, tex);
	}
	return 0;
}

static int lua_ufoButtonSetHoverImage(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	const char *texture = lua_tostring(L, -1);
	UFO_Texture tex = ufoResourceGetTexture(texture);
	if (texture) {
		ufoButtonSetHoverImage(view, tex);
	}
	return 0;
}

static int lua_ufoButtonSetTouchedImage(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	const char *texture = lua_tostring(L, -1);
	UFO_Texture tex = ufoResourceGetTexture(texture);
	if (texture) {
		ufoButtonSetTouchedImage(view, tex);
	}
	return 0;
}

static const struct luaL_Reg buttonlib [] = {
	{"setNormalTexture", lua_ufoButtonSetNormalImage},
	{"setHoverTexture", lua_ufoButtonSetHoverImage},
	{"setTouchedTexture", lua_ufoButtonSetTouchedImage},
	{0, 0},
};

int internal_initializationScript_buttonview()
{
	if (!g_ufo_lua_state) {
		g_ufo_lua_state = luaL_newstate();
		luaL_openlibs(g_ufo_lua_state);
	}

	luaL_newmetatable(g_ufo_lua_state, "ufo.ufoView");

	lua_pushvalue(g_ufo_lua_state, -1);
	lua_setfield(g_ufo_lua_state, -2, "__index");

	luaL_register(g_ufo_lua_state, 0, buttonlib);

	return 1;
}